<extend name="./public/frame.html"/>
<block name="content">
    <style>
        .box{display: flex}
        .box .flex{width: 50%}
        .box .flex .layui-laydate{width: 90%; margin: 18px;}
        .box .flex .layui-laydate .layui-laydate-main{width: 100%}
        .box .flex .layui-laydate .layui-laydate-main .layui-laydate-content table{width: 100%}
        ul li{margin-left: 10px}
    </style>
    <div class="box">
        <div class="flex"><table class="layui-table" lay-filter="custom" id="custom"></table><b style="color: red;">注：排班前，请先勾选相应的客服人员。</b></div>
        <div id="calender" class="flex"></div>
    </div>
    <form action="" method="post" class="layui-form">
        <ul class="box" style="height: 20px">
            <li id="start"></li>
            <li id="end"></li>
            <li id="btn"></li>
        </ul>
        <table class="layui-table" lay-filter="schedule" id="schedule"></table>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="submit">立即提交</button>
                <!--<button type="reset" class="layui-btn layui-btn-primary">重置</button>-->
            </div>
        </div>
    </form>
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>
    </script>
    <script>
        Array.prototype.remove = function(val) {
            var index = this.indexOf(val);
            if (index > -1) {
                this.splice(index, 1);
            }
        };
        Array.prototype.del = function(index) {
            if (index > -1) {
                this.splice(index, 1);
            }
        };
        Array.prototype.clear = function() {
            this.splice(0,this.length);
        };
        var css = new Array(),schedule = new Array(),data = new Array(),csi = new Array(),temp = new Array();
        var start = $('#start'),end = $('#end'),btn = $('#btn'),tableIns;
        layui.use(['table','laydate','form'], function () {
            var table = layui.table,form = layui.form,laydate = layui.laydate;
            table.render({
                elem:"#custom",
                id: 'custom',
                url:"{$url}",
                cols: [[
                    {checkbox:true,title:"",fixed: true},
                    {title:"ID",field:'id', width:60, fixed: true, sort: true},
                    {title:"客服姓名",field:'cus_name', width:100},
                ]],
                page:true,
                limit:10,
                done: function(res, curr, count){
                    _cur_page = curr;
                    _cur_limit = res['limit'];
                    _count = count;
                    res['data'].forEach(function (val) {
                        csi[val['admin_id']] = val['cus_name'];
                    });
                }
            });
            tableIns = table.render({
                elem:"#schedule",
                data:[],
                cols: [[
                    {title:"客服",field:'name', width:100},
                    {title:"开始时间",field:'start', width:180},
                    {title:"结束时间",field:'end', width:180},
                    {title:"操作",fixed:'right', toolbar: '#barDemo', width:100, align:'center'}
                ]],
                page:true,
                limit:10
            });
            form.on('submit(submit)',function (data) {
                if(schedule.length==0){
                    layer.alert('请先添加计划');
                    return false;
                }
                $.post('/admin/custom/schedule',{data:schedule},function (res) {
                    schedule.clear();
                    switch (res['status']){
                        case 1:
                            window.location.href = "/admin/custom/list_";
                            break;
                        default:
                            layer.alert(res['msg'],{icon: 5});
                            break;
                    }
                },'json');
                return false;
            });
            //监听表格复选框选择
            table.on('checkbox(custom)', function(obj){
                var checkStatus = table.checkStatus('custom'),all_data = checkStatus.data,all_checked = checkStatus.isAll
                    ,type=obj.type,checked=obj.checked,data=obj.data;
                switch (type){
                    case 'one':
                        if(checked){
                            css.push(data.admin_id);
                        }else{
                            css.remove(data.admin_id);
                        }
                        break;
                    case 'all':
                        if(checked){
                            all_data.forEach(function (val) {
                                css.push(val.admin_id);
                            });
                        }else{
                            css.clear();
                        }
                        break;
                }
            });
            table.on('tool(schedule)', function (obj) {
                var data = obj.data; //获得当前行数据
                var id = data.id;
                var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                if(layEvent === 'del'){
                    layer.confirm('确定删除吗?',{icon:3}, function (index) {
                        var ind = schedule.length - id;
                        schedule.del(ind);
                        temp.del(ind);
                        dealTemp();
                        layer.close(index);
                    });
                }
            });
            var d = '';
            laydate.render({
                elem: '#calender'
                ,position: 'static'
                ,calendar: true
                ,type: 'datetime'
                ,format: 'yyyy-MM-dd HH:00:00'
                ,done: function(value, date, endDate){
                    d = value;
                }
            });
            var btns = $(document).find(".laydate-footer-btns span");
            var str = '',str2='';
            btns.each(function (index,element) {
                element.addEventListener("click",function(){
                    var flag = $(this).attr('lay-type');
                    switch (flag){
                        case 'now':
                        case 'confirm':
                            if(css.length==0){
                                layer.alert('请先选择需要排班的客服',{icon:7});
                                return false;
                            }
                            if(start.html()==''){
                                str = '开始时间:';
                                start.html(str+d);
                                data.push(d);
                            }else{
                                if(data.length==1){
                                    data.push(d);
                                    str = '结束时间:';
                                    end.html(str+d);//JSON.stringify(tableIns)
                                    str2 = "<a class='layui-btn layui-btn-xs layui-btn-normal' onclick='confirm()'>确认</a>";
                                    str2 += "<a class='layui-btn layui-btn-xs layui-btn-danger' onclick='cancel()'>取消</a>";
                                    btn.html(str2);
                                }
                            }
                            break;
                    }
                },false)
            });
        });

        function confirm() {
            css.forEach(function (value) {
                var str = '{',str2 = '{';
                str += "\"admin_id\":\"" + value + '",';
                str2 += "\"name\":\"" + csi[value] + '",';
                str += "\"start_time\":\"" + data[0] + '",';
                str2 += "\"start\":\"" + data[0] + '",';
                str += "\"end_time\":\"" + data[1] + '"';
                str2 += "\"end\":\"" + data[1] + '"';
                str += "}";
                str2 += "}";
                schedule.unshift(JSON.parse(str));
                temp.unshift(JSON.parse(str2));
            });
            cancel();
            dealTemp()
        }
        function cancel() {
            data.clear();
            start.html('');
            end.html('');
            btn.html('');
        }
        function dealTemp() {
            temp.forEach(function (val,index,arr) {
                temp[index]['id'] = arr.length - index;
            });
            tableIns.reload({data:temp})
        }
    </script>
</block>
